package com.javasm.utils;

import com.javasm.error.ExceptionEnum;
import com.javasm.error.JavasmException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @className: EmailTemplate
 * @description
 * @author: gfs
 * @date: 2024/7/15 15:27
 * @version: 0.1
 * @since : jdk11
 */
@Component
public class EmailTemplate {
    private final static Logger LOGGER = LogManager.getLogger(EmailTemplate.class);

    @Resource
    JavaMailSender mailSender;
    //配置文件中的内容 都在这个对象里
    @Resource
    MailProperties mailProperties;

    public void sendEmail(String email, String title, String count) {
        sendEmail(email, title, count, null);
    }

    public void sendEmail(String email, String title, String count, File... files) {
        //获取 消息对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            //创建 辅助类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //设置 发送人
            helper.setFrom(mailProperties.getUsername());
            //设置 收件人
            helper.setTo(email);
            //设置 标题
            helper.setSubject(title);
            //设置内容
            helper.setText(count, true);
            //处理附件
            if (files != null && files.length > 0) {
                for (File f : files) {
                    //如果是图片
                    if (isImage(f)){
                        helper.addInline("ei",f);
                    }
                    //上传附件
                    helper.addAttachment(f.getName(),f);
                }
            }
            //发送操作
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            LOGGER.error(e.getMessage());
            throw new JavasmException(ExceptionEnum.EmailSendError);
        }
    }

    private boolean isImage(File file) {
        try {
            //把file对象 转成  image对象
            //如果 转换成功,不是null,说明  是图片
            BufferedImage image = ImageIO.read(file);
            return image != null;
        } catch (IOException e) {
            //如果 进入 catch 说明 转换失败,不是图片
            return false;
        }
    }
}
